import 'dart:convert';
import 'package:rfid/log/logger_manager.dart';
import 'package:rfid/socket/result_handler.dart';
import 'package:rfid/socket/socket.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class SocketHelper{


  ResultHandler resultHandler = ResultHandler();

  static final Map<String, SocketHelper> _cache = <String, SocketHelper>{};
  final String url;

  factory SocketHelper(String url) {
    return _cache.putIfAbsent(url, () => SocketHelper._internal(url));
  }

  SocketHelper._internal(this.url){
    initSocket(url);
  }

  late WebSocketChannel channel;
  void initSocket(url){
    LoggerManager().write("Socket manager", 'Socket is init');
    channel =  IOWebSocketChannel.connect(Uri.parse(url));
    sendListen();
    add(checkRfid());
    add(checkLock());
    add(checkReader());
  }

  void sendListen() {
    print('重连');
    LoggerManager().write("Socket manager", 'Socket is Reconnect');
    channel.stream.listen(onData,onError: onError, onDone: onDone );
  }

  void add(msg){
    LoggerManager().write("Socket manager", 'send $msg');
    channel.sink.add(msg);
  }

  void onDone()async{
    LoggerManager().write("Socket manager", 'Socket is closed');
    print("Socket is closed");
    reconnect();
  }

  void onError(err){
    print(err);
    // reconnect();
  }

  void reconnect(){
    Future.delayed(const Duration(seconds:10),(){
      initSocket(url);
    });
  }

  void onData(event){
    LoggerManager().write("Socket manager", 'received $event');
    print('收到消息：$event');
    resultHandler.handler(jsonDecode(event));

  }


  void dispose() {
    print('关闭');
    channel.sink.close();
  }
}